using System.Text.RegularExpressions;
using global::GoGameClient.script.global;
using Godot;
using GoGameClient.script.cmd;
using GoGameClient.script.dialog;
using GoGameClient.script.network.webSocket;
using Script.Message.Req;
using Script.Message.Res;

namespace GoGameClient.script.node.caption;

public partial class RegisterControl : Control
{
    private LineEdit _account;
    private LineEdit _qq;
    private LineEdit _password;
    private LineEdit _detectionPassword;

    public override void _Ready()
    {
        _account = GetNode<LineEdit>("Account");
        _qq = GetNode<LineEdit>("QQ");
        _password = GetNode<LineEdit>("Password");
        _detectionPassword = GetNode<LineEdit>("DetectionPassword");
    }

    private void OnConfirmPressed()
    {
        var qqText = _qq.Text;
        var accountText = _account.Text;
        var passwordText = _password.Text;
        var detectionPasswordText = _detectionPassword.Text;
        if (Verify(accountText, passwordText, detectionPasswordText, qqText)) return;
        var socketRequestConfig = new BodyRequestConfig<RegisterReq, SuccessRes>
        {
            Title = "注册用户",
            Cmd = (int)Router.User,
            CmdMethod = (int)UserRouter.Register,
            Data = new RegisterReq
            {
                Account = accountText,
                Password = passwordText,
                Qq = qqText
            },
            Result = message => { TipsDialogUtil.ShowTips(this, $"注册{message.Message}"); }
        };
        SocketControl.Instance().Request(socketRequestConfig);
    }

    private bool Verify(string accountText, string passwordText, string detectionPasswordText, string qqText)
    {
        if (accountText.Equals(""))
        {
            TipsDialogUtil.ShowTips(this, "请输入账户");
            return true;
        }

        if (passwordText.Equals(""))
        {
            TipsDialogUtil.ShowTips(this, "请输入密码");
            return true;
        }

        if (detectionPasswordText.Equals(""))
        {
            TipsDialogUtil.ShowTips(this, "请输入确认密码");
            return true;
        }

        if (qqText.Equals(""))
        {
            TipsDialogUtil.ShowTips(this, "请输入确认QQ号");
            return true;
        }

        var regex = new Regex(@"[\u4e00-\u9fa5]"); // Unicode编码范围内的汉字
        if (regex.IsMatch(accountText))
        {
            TipsDialogUtil.ShowTips(this, "不能用中文账号");
            return true;
        }

        if (passwordText.Length < 6)
        {
            TipsDialogUtil.ShowTips(this, "密码最少6位数");
            return true;
        }

        if (passwordText.Equals(detectionPasswordText)) return false;
        TipsDialogUtil.ShowTips(this, "密码不一致");
        return true;
    }

    private void OnCancelPressed()
    {
        Visible = false;
    }
}